//
//  XMMainViewController.swift
//  XMWeibo-Swift
//
//  Created by 育鑫 王 on 15/10/27.
//  Copyright © 2015年 育鑫 王. All rights reserved.
//

import UIKit

class XMMainViewController: UITabBarController {
    
    func addButtonDidClick(){
        print(__FUNCTION__)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tabBar.tintColor = UIColor.orangeColor()
        
        
//        let newTabBar = XMMainTabBar()
//        newTabBar.addButton.addTarget(self, action: "addButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //使用KVC
//        setValue(newTabBar, forKey: "tabBar")
        
        //添加首页
        let homeVc = XMHomeViewController()
        addChildViewController(homeVc, title: "首页", imageName: "tabbar_home")
        
        //添加消息
        let messageVc = XMMessageViewController()
        addChildViewController(messageVc, title: "消息", imageName: "tabbar_message_center")
        
        //再添加一个占位控制器 方便处理事件
        let controller = UIViewController()
        addChildViewController(controller, title: "", imageName: "e")
        
        //添加发现
        let discoverVc = XMDiscoverViewController()
        addChildViewController(discoverVc, title: "发现", imageName: "tabbar_discover")
        
        //添加我
        let profileVc = XMProfileViewController()
        addChildViewController(profileVc, title: "我", imageName: "tabbar_profile")
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        let width = tabBar.bounds.width / CGFloat(5)
        addButton.frame = CGRect(x:width * 2 , y: 0, width: width, height: tabBar.bounds.height)
        tabBar.addSubview(addButton)
    }
    
    /**
    添加子控制器，包装Nav
    
    - parameter controller: 控制器
    - parameter title:      标题
    - parameter imageName:  图片名称
    */
    private func addChildViewController(controller: UIViewController, title: String, imageName: String){
        controller.title = title
        controller.tabBarItem.image = UIImage(named: imageName)
        
        addChildViewController(UINavigationController(rootViewController: controller))
        
    }
    
    //添加中间按钮
    lazy var addButton : UIButton = {
        let button = UIButton()
        
        // 按钮图片
        button.setImage(UIImage(named:"tabbar_compose_icon_add" ), forState: UIControlState.Normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted" ), forState: UIControlState.Highlighted)
        
        //按钮背景
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "addButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
